/**
 * 
 */
package com.zznode.client.wlanpolling.utils;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.telephony.TelephonyManager;

/**
 * @author Bean
 * 
 */
public class PingUtils {
	private static String keyLost = "received, ";
	private static String keyDelay = "rtt min/avg/max/mdev = ";

	public static boolean isEmulator(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId();
		if (imei == null || imei.equals("000000000000000")) {
			return true;
		}
		return false;
	}

	public static String[] parsePingResultParse(String str) {
		String[] as = new String[6];
		as[0] = str;
		
		//平均丢包率
		int index = str.indexOf(keyLost);
		if (index != -1) {
			if (as.length > 3) {
				String transmitted = str.substring(0, str.indexOf(" "));
				int firstIndex = str.indexOf(", ");
				int lastIndex = str.indexOf(" ", firstIndex + 3);
				String received = str.substring(firstIndex + 2, lastIndex);
				//丢包数
				as[3] = (Integer.parseInt(transmitted) - Integer
						.parseInt(received)) + "";
			}
			int sIndex = str.indexOf("%", index);
			//丢包率
			as[2] = str.substring(index + keyLost.length(), sIndex);
		}
		
		//平均延迟
		index = str.indexOf(keyDelay);
		int sIndex = -1, nextIndex = -1;
		if (index != -1) {
			sIndex = str.indexOf("/", index + keyDelay.length());
			nextIndex = str.indexOf("/", sIndex + 1);
			//最小延迟
			as[1] = str.substring(sIndex + 1, nextIndex);
		}		
		if(index != -1 && sIndex != -1 && nextIndex != -1 && as.length > 3){
			//平均延迟
			as[4] = str.substring(index + keyDelay.length(), sIndex);
			sIndex = str.indexOf("/", sIndex + 1);
			nextIndex = str.indexOf("/", sIndex + 1);
			//最大延迟
			as[5] = str.substring(sIndex + 1, nextIndex);
		}
		
		return as;
	}

	/**
	 * 获取精度和纬度
	 * @param context
	 * @return
	 */
	public static double[] getLocationInfo(Context context) {
		LocationManager locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		Location location = locationManager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		if (location != null) {
			return new double[] { location.getLatitude(),
					location.getLongitude() };
		}

		location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location != null) {
			return new double[] { location.getLatitude(),
					location.getLongitude() };
		}

		return new double[] { -1, -1 };

	}
	
	public static String clearMacAdress(String macAddress) {
		if(macAddress == null)
			return null;
		
		return macAddress.replace(":", " ").toUpperCase();
	}

}
